package com.lu.stream;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Date:2021/11/27/10:00
 * @Description: 流的算子操作
 */
public class EmployeeData {
    // filter,map 使用实例
    @Test
    public void test01(){
        List<StreamApi.Employee> employeeList = new StreamApi().getEmployeeList();
        Stream<StreamApi.Employee> stream = employeeList.stream();

        Stream<StreamApi.Employee> employeeStream = stream.filter(elem -> elem.age > 40);
        Stream<Person> personStream = employeeStream.map(x -> {
            String name = x.name;
            int bigAge = x.age * 100;
            return new Person(name, bigAge);
        });
        personStream.forEach(System.out::println);
    }

    //flatMap( Function f )--接收一个函数作为参数，将流中的每个值都换成另一个流，然后把所有流都连接一起
    @Test
    public void test02(){
        ArrayList list = new ArrayList();
        list.add("aa");
        list.add("bb");

        ArrayList list2 = new ArrayList();
        list2.add("5");
        list2.add("6");

        list.add(list2);
        System.out.println("list = " + list);


        Stream stream = list.stream();


        Stream<String> stream1 = stream.flatMap(elem -> {  // {1,2,3,{11,22,33}}  --> {1,2,3,11,22,33}  这类非规则需要进行判断
            ArrayList<String> objects = new ArrayList<>();
            if (elem instanceof List) {
                for (Object i : (List) elem) {
                    objects.add(i.toString());
                }
            } else {
                objects.add(elem.toString());
            }
            return objects.stream();
        });
        stream1.forEach(System.out::println);
    }

    @Test
    public void test04(){
        List<String> list = Arrays.asList("aa", "bb");

        Stream<Character> characterStream = list.stream().flatMap(elem -> EmployeeData.fromStringToStream(elem));
        characterStream.forEach(System.out::println);


    }

    public static Stream<Character> fromStringToStream(String str){
        char[] chars = str.toCharArray();
        ArrayList<Character> list = new ArrayList<>();
        for(Character c : chars){
            list.add(c);
        }
        return list.stream();
    }

    // 测试 流的收集操作 collect
    @Test
    public void test05(){
        List<String> list = Arrays.asList("12", "34", "45");
        Set<String> collect = list.stream().filter(elem -> elem.contains("34")).collect(Collectors.toSet());
        System.out.println(collect.toString());
    }


}
class Person{
    String name;
    int age;

    public Person(String name,int age){
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}